package com.example.m2m.service.impl;

import com.example.m2m.mapper.UserMapper;
import com.example.m2m.pojo.Role;
import com.example.m2m.pojo.User;
import com.example.m2m.service.UserRoleService;
import com.example.m2m.util.MyBatisUtil;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Author 宋伟宁
 * @Date 2023/9/8
 * @Version 1.0
 **/
public class UserRoleServiceImpl implements UserRoleService {

    private static final Logger logger = LoggerFactory.getLogger(UserRoleService.class);
    private final SqlSession session = MyBatisUtil.getInstance();
    private final UserMapper userMapper =session.getMapper(UserMapper.class );
    @Override
    public PageInfo<User> users(String offset) {
        offset = offset == null ? "1": offset;
        int start=Integer.parseInt(offset);
         com.github.pagehelper.PageHelper.startPage(start,5);
         PageInfo<User> pager=new PageInfo<>(this.userMapper.users());
        return pager;
    }

    @Override
    public User login(String name, String pwd) {
        return null;
    }

    @Override
    public List<Role> findRolesByUser(int id) {
        return this.userMapper.findRolesByUser(id);
    }

    @Override
    public boolean saveUser(User user, String[] ids) {
       Integer id= user.getId();
        System.out.println("保存的用户id"+id);
        System.out.println("roles---->"+ids.toString());
        int m=0;
        try {
            if (id == null || id == 0) {
                //新增
                m = this.userMapper.addUser(user);
                System.out.println("新增用户"+user);
                m += this.addUserRole(user.getId(), ids);
            } else {
                //修改
                m = this.userMapper.updateUser(user);
                m += this.userMapper.delUseruid(id);
                m += this.userMapper.addUserRole(id, ids);
            }
            if (m >= 2) {
                this.session.commit();
            } else {
                this.session.rollback();
            }
        }catch (Exception e){
            logger.debug("保存用户错误"+e.getMessage());
        }
        return m>=2;
    }

    @Override
    public int addUserRole(int uid, String[] ids) {
        return this.userMapper.addUserRole(uid,ids);
    }

    @Override
    public List<Role> roles() {
        return this.userMapper.roles();
    }

    @Override
    public boolean delete(String ids) {
        String[] arr = ids.split(",");
        int m = this.userMapper.deleteMiddle(arr);
        m += this.userMapper.delUser(arr);
        if(m>=2){
            this.session.commit();
            return  true;
        }
        return false;

    }

    @Override
    public User findUser(String id) {
        return this.userMapper.findUserById(id);
    }
}
